package util

import (
	"net"
	"net/http"
	"sync"
	"time"
)

type HttpClientMap struct {
	lock    sync.Mutex
	clients map[string]*http.Client
}

func (m *HttpClientMap) GetHttpClient(name string) *http.Client {
	v, ok := m.clients[name]
	if ok {
		return v
	}

	m.lock.Lock()
	defer m.lock.Unlock()

	v, ok = m.clients[name]
	if ok {
		return v
	}
	v = &http.Client{
		Transport: &http.Transport{
			DialContext: (&net.Dialer{
				Timeout:   30 * time.Second,
				KeepAlive: 30 * time.Second,
			}).DialContext,
			DisableKeepAlives:      false,
			DisableCompression:     false,
			MaxIdleConns:           32,
			MaxIdleConnsPerHost:    32,
			MaxConnsPerHost:        256,
			IdleConnTimeout:        30 * time.Second,
			ResponseHeaderTimeout:  0,
			ExpectContinueTimeout:  0,
			MaxResponseHeaderBytes: 8192,
			WriteBufferSize:        16384,
			ReadBufferSize:         16384,
			ForceAttemptHTTP2:      false,
		},
		Timeout: time.Duration(3 * time.Minute),
	}
	m.clients[name] = v
	return v
}

func NewHttpClientMap() *HttpClientMap {
	return &HttpClientMap{clients: make(map[string]*http.Client, 64)}
}
